package com.example.tanhuanapp.server.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tanhuanapp.mapper.UserMapper;
import com.example.tanhuanapp.pojo.User;
import com.example.tanhuanapp.server.UserServer;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author IT空门_门主
 * @date 2024/1/9
 */
@Slf4j
@Service
public class UserServerImpl extends ServiceImpl<UserMapper, User> implements UserServer  {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private  UserMapper userMapper;
    @Value("${jwt.secret}")
    private String secret;
    /**
     * 获取手机号码生成token
     * @param phone
     * @param verificationCode 
     */
    @Override
    public String userLogin(String phone, String verificationCode) {
        //检验验证码是否正确
        //redis头
        String redisKey = "CHECK_CODE:" + phone;
        /**
         * 如果redis中有就进行查询-返回
         */
        String redisCode= stringRedisTemplate.opsForValue().get(redisKey);
        //验证码为空
        if (StringUtils.isEmpty(redisCode)){
           return null;
        }
        //验证码错误
        if(!redisCode.equals(verificationCode)){
            return null;
        }
        //默认为已注册
        boolean isNew=true;
        //如果没有注册是新用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        User user = userMapper.selectOne(queryWrapper);
        log.info("用户信息{}",user);
        //获取用户
        User user1 =  new User();;
        if (user==null){
            //新用户注册
            user1.setMobile(phone);
            //默认密码为123456
            user1.setPassword(DigestUtil.md5Hex(secret+"_123456"));
            //时间
            user1.setCreated(new Date());
            user1.setUpdated(new Date());
            userMapper.insert(user1);
            isNew=false;
        }
        //不是新用户
        Map<String, Object> claims = new HashMap<>();
        claims.put("mobile", phone);
        claims.put("id",user1.getId());

        //生成token
        String token= Jwts.builder()
                //设置响应数据体
                .setClaims(claims)
                //设置加密方法和加密盐
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
       log.info("生成的Token:{}",token);
        //将Token写入数据库
        String redisTokenKey="TOKEN_"+token;
        //保存到redis-时间为1小时 (Token中存的是登录的信息)
        stringRedisTemplate.opsForValue().set(redisTokenKey, JSONUtil.toJsonStr(user1),1, TimeUnit.HOURS);
        //todo 发送消息暂时没有

        return isNew + "|" + token;
    }
}
